/*
 * File    : /src/views/task/const.js
 * Time    : 2021-09-28 16:00:20
 * Author  : Gray Snail
 * Version : 1.0
 * Contact : shtao2011@sina.com
 * License : Copyright (c) 2021 Gray Snail
 * Desc    : None
 */

import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)

const labelFn = (initMsg, msg) => {
  return (repeat) => {
    return repeat ? msg + ' ' + repeat : initMsg
  }
}

export const WorkflowStatusMap = Object.freeze([
  { label: '新建', value: 0 },
  { label: '分包', value: 1 },
  { label: labelFn('标注', '返修'), value: 2 },
  { label: labelFn('工厂质检', '工厂复检'), value: 3 },
  { label: labelFn('工厂验收', '工厂复验'), value: 4 },
  { label: labelFn('平台质检', '平台复检'), value: 5 },
  { label: labelFn('平台验收', '平台复验'), value: 6 },
  { label: labelFn('企业质检', '企业复检'), value: 7 },
  { label: labelFn('企业验收', '企业复验'), value: 8 },
  { label: '完成', value: 9 },
])

export const TaskStatus = Object.freeze([
  { label: '待领取', value: 0 },
  { label: '进行中', value: 1 },
  { label: '撤回', value: 2 },
  { label: '完成', value: 3 },
])

export const formatStatus = (workflow) => {
  const { status } = workflow
  const label = TaskStatus.find((stat) => stat.value == status)?.label
  return label || '未知'
}

export const formatTaskStatus = (workflow) => {
  const { taskStatus: status } = workflow
  if (status == undefined) {
    return ''
  }

  const step = parseInt(status / 10)
  const repreat = status - step * 10
  const label = WorkflowStatusMap.find((stat) => stat.value == step)?.label
  if (label instanceof String) {
    return label + ' ' + repreat
  } else if (label instanceof Function) {
    return label(repreat)
  } else {
    return label
  }
}

export const formatReason = (workflow) => {
  if (workflow.status == 2) {
    return ['管理员撤回', '用户撤回', '超时撤回'][workflow.reason - 1]
  } else if (workflow.status == 3) {
    return ['通过', '不通过'][workflow.reason - 1]
  } else {
    return ''
  }
}

export const formatTime = (workflow) => {
  let prefix, time
  if (workflow.status == 0) {
    prefix = '已等待'
    time = dayjs.duration(dayjs() - dayjs(workflow.createTime, 'YYYY-MM-DD HH:mm:ss'))
  } else if (workflow.status == 1) {
    prefix = '已进行'
    time = dayjs.duration(dayjs() - dayjs(workflow.startTime, 'YYYY-MM-DD HH:mm:ss'))
  } else {
    prefix = '总用时'
    time = dayjs.duration(
      dayjs(workflow.finishTime, 'YYYY-MM-DD HH:mm:ss') - dayjs(workflow.startTime, 'YYYY-MM-DD HH:mm:ss')
    )
  }
  const days = time.asDays()
  if (days > 1) {
    return `${prefix} ${time.format('DD天HH:mm:ss')}`
  } else {
    return prefix + time.format(' HH:mm:ss')
  }
}

export const getStep = (status) => {
  if (status == undefined) return 0
  const step = parseInt(status / 10)
  return step
}
